package com.test;

import java.io.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;



public class FileChooserDemo extends JPanel
                             implements ActionListener {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static private final String newline = "\n";
    JButton openButton, logReadBtn;
    JTextArea log;
    JFileChooser fc;
    JTextField filePath;

    public FileChooserDemo() {
        super(new BorderLayout());
        filePath = new JTextField();
        filePath.setEditable(false);
        log = new JTextArea(20,40);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        JScrollPane logScrollPane2 = new JScrollPane(filePath);
        
        JScrollPane logScrollPane = new JScrollPane(log);

     
        fc = new JFileChooser(new File("C:\\test"));

        
        fc = new JFileChooser(); 
        fc.setCurrentDirectory(new java.io.File("D:/UBRFx"));
       // fc.setDialogTitle(choosertitle);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        
        
        
        openButton = new JButton("Choose a Directory...");
        openButton.addActionListener(this);

        logReadBtn = new JButton("Read Log...");
        logReadBtn.addActionListener(this);
  
        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openButton);
        
        buttonPanel.add(logReadBtn);

        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane2, BorderLayout.CENTER);
        add(logScrollPane, BorderLayout.PAGE_END);
    }

    public void actionPerformed(ActionEvent e) {
    	BufferedReader br = null;
		String fileName = null;
		String sCurrentLine = null;
		BufferedWriter bw = null;
        //Handle open button action.
        if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(FileChooserDemo.this);
            log.setText("");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                
        		try{
        			filePath.setText("");
        			filePath.setText(file.getAbsolutePath());
        			
        			File logFile = new File("C:\\test\\logfile.txt");
       			 
        			// if file doesnt exists, then create it
        			if (!logFile.exists()) {
        				logFile.createNewFile();
        			}
        			log.append("Log File Path : " + logFile.getAbsolutePath() + "." + newline);
        			
        			bw = new BufferedWriter( new FileWriter(logFile.getAbsoluteFile()));
        			
        			//String fileName = "D:\\UBRFx";
        			//File file1 = new File(file_ch);
        			bw.write("Check for  path : " + file.getAbsolutePath());
        			bw.newLine() ;
        			String[] directories = file.list(new FilenameFilter() {
        				  @Override
        				  public boolean accept(File dir, String name) {
        				    return new File(dir, name).isDirectory();
        				  }
        				});
        			int count = 0;
        			int countD = 0;
        			for(int i=0; i<directories.length; i++ ){
        				int d = checkEmpty(new File(fileName+"\\"+directories[i]));
        				if ( d==0){
        					bw.newLine() ;
        					bw.write(directories[i] + "   is  empty");
        					bw.newLine() ;
        					System.out.println(directories[i] + "   is  empty");
        					count++;
        				}
        				if(d == 1){
        					countD++;
        				}
        			}
        			bw.newLine() ;
        			bw.write("---------------------------------------------");
        			bw.newLine() ;
        			bw.write("Total Empty Dir : " + count);
        			bw.newLine() ;
        			bw.write("Total Non Empty Dir : " + countD);
        			bw.newLine() ;
        			bw.write("---------------------------------------------");
        			bw.newLine() ;
        			bw.write("Total Dir : " +( count+countD));
        			bw.newLine() ;
        			
        			System.out.println("---------------------------------------------");
        			System.out.println("Total Empty Dir : " + count);
        			System.out.println("Total Non Empty Dir : " + countD);
        			System.out.println("---------------------------------------------");
        			System.out.println("Total Dir : " +( count+countD));
        			bw.close();
        			log.append("********Done**********" + "." + newline);
        		}catch(Exception exx){
        			
        		}
                
                //This is where a real application would open the file.
               // log.append("File Text: " + fileName + "." + newline);
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());

        //Handle save button action.
        } else if (e.getSource() == logReadBtn) {
            
           log.setText("");
           File logFile = new File("C:\\test\\logfile.txt");
           try {
			br = new BufferedReader(new FileReader(logFile));
			while ((sCurrentLine = br.readLine()) != null) {
				//System.out.println(sCurrentLine);
				log.append("Path to check empty Directory " + sCurrentLine + "." + newline);
				
			}
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
			
			
			
           
           
        }
    }


    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FileChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.
        frame.add(new FileChooserDemo());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE); 
                createAndShowGUI();
            }
        });
    }
    public static int checkEmpty(File subDir){
		int sta = 0;
		if(subDir.isDirectory()){
			if(subDir.list().length>0){
				sta =1;
			}else{
				sta =0;
			}
		}
		return sta;
	}
}
